/**
  HomeMade by shoe[box]
 
  Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice, 
    this list of conditions and the following disclaimer.
  
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the 
    documentation and/or other materials provided with the distribution.
  
  * Neither the name of shoe[box] nor the names of its 
    contributors may be used to endorse or promote products derived from 
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.shoebox.guacamole.assets {

	import org.shoebox.collections.HashMap;
	import org.shoebox.guacamole.materials.BitmapMaterial;
	import org.shoebox.guacamole.materials.GuaTexture;
	import org.shoebox.guacamole.materials.abstracts.AMaterial;
	import org.shoebox.guacamole.view.GuaScene;
	import org.shoebox.utils.logger.Logger;
	import mx.core.BitmapAsset;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display3D.Context3DTextureFormat;
	import flash.display3D.textures.Texture;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	/**
	* org.shoebox.guacamole.assets.AssetManager
	* @author shoebox
	*/
	public class AssetManager {
		
		protected var _hCache					: HashMap;
		
		static protected var _dCacheByClass			: Dictionary = new Dictionary( true );
		static protected var _oScene					: GuaScene;
		
		// -------o constructor
		
			/**
			* Constructor of the AssetManager class
			*
			* @public
			* @return	void
			*/
			public function AssetManager( e : SingletonEnforcer ) : void {
				_hCache = new HashMap( true );
			}

		// -------o public
			
			/**
			* getTextureFromClass function
			* @public
			* @param 
			* @return
			*/
			static public function getTextureFromClass( c : Class , bCompressed : Boolean = false ) : GuaTexture {
				
				if( _dCacheByClass[ c ] !==undefined )
					return _dCacheByClass[ c ];
					
				var tTex : GuaTexture;
				var source : * = new c( );
				if( source is BitmapAsset ){
					tTex = getTextureFrombitmapData( ( source as BitmapAsset ).bitmapData );
				}else if( source is ByteArray ){
					tTex = getTextureFromRawATF( source as ByteArray );
				}
				
				_dCacheByClass[ c ] = tTex;
				//TODO : Bytearray / compressed
				
				return tTex;	
			}
			
			/**
			* getTextureFromByteArray function
			* @public
			* @param 
			* @return
			*/
			static public function getTextureFromRawATF( a : ByteArray  ) : GuaTexture {
				
				var		iW : int = Math.pow ( 2 , a[7] );
				var		iH : int = Math.pow ( 2 , a[8] );
				
				var		oTex : Texture = _oScene.refContext3D.createTexture( iW , iH , Context3DTextureFormat.BGRA , false );
						oTex.uploadCompressedTextureFromByteArray( a , 0 );
						
				var 	tRes : GuaTexture = new GuaTexture( oTex , iW , iH );
				
				return tRes;
			}
			
			/**
			* getTextureFrombitmapData function
			* @public
			* @param 
			* @return
			*/
			static public function getTextureFrombitmapData( source : BitmapData ) : GuaTexture {
				var		oTex : Texture = _oScene.refContext3D.createTexture( source.width , source.height , Context3DTextureFormat.BGRA , false );
						oTex.uploadFromBitmapData( source );
				
				return new GuaTexture( oTex , source.width , source.height );

			}
			
			/**
			* Add a new <code>GuaScene</code> reference by ID
			* 
			* @public
			* @param	id : Stage id		( int )
			* @param 	scene : Scene reference	( GuaScene ) 
			* @return
			*/
			static public function setStageRef( oScene : GuaScene ) : void {
				_oScene = oScene;
			}
			
			/**
			* fromBitmapData function
			* @public
			* @param 
			* @return
			*/
			static public function fromBitmapData( 
														source 	: BitmapData , 
														bRepeat : Boolean = false 
													) : BitmapMaterial {
						
				var 	oMat : BitmapMaterial = new BitmapMaterial( getTextureFrombitmapData( source ).tTexture , source.width , source.height , bRepeat ); 
						oMat.refScene = _oScene;
						
				return oMat;
			
			}
			
			/**
			* getMaterial function
			* @public
			* @param 
			* @return
			*/
			static public function getMaterial( 
										source : * ,  
										matType : Class = null ,
										sceneId : int = 0, 
										w : int = -1 , h : int = -1 , 
										bCompress : Boolean = false
									) : AMaterial {
					
				
				if( matType == null ){
					
					var bmp : BitmapData;
					if( source is BitmapAsset )
						bmp = ( source as BitmapAsset ).bitmapData;
					else if( source is Bitmap )
						bmp = ( source as Bitmap ).bitmapData;
					else if( source is BitmapData )
						bmp = source;
						
					return getInstance( ).getMaterial( source , _oScene , BitmapMaterial , bmp.width , bmp.height , false );
					
				}
				
						
				return getInstance( ).getMaterial( source , _oScene , matType , w , h , bCompress );
			}
				
			/**
			* getBitmapMaterial function
			* @public
			* @param 
			* @return
			*/
			static public function getBitmapMaterial( 
										source : * ,  
										sceneId : int = 0, 
										w : int = -1 , h : int = -1 ,
										bRepeat		: Boolean = false, 
										bCompress	 : Boolean = false
									) : BitmapMaterial {
										
				return getInstance( ).getMaterial( source , _oScene , BitmapMaterial , w , h , bCompress , bRepeat ) as BitmapMaterial;
				
			}
			
			/**
			* getTexture function
			* @public
			* @param 
			* @return
			*/
			final public function getMaterial( 
										ref 		: * , 
										scene		: GuaScene , 
										matType 	: Class = null , 
										w 			: int = -1 , 
										h 			: int = -1 , 
										bCompress 	: Boolean = false ,
										bRepeat		: Boolean = false
									) : AMaterial {
				
				if( _hCache.containsKey( ref ) ){
					trc('useCache');
					return _hCache.getValue( ref ) as AMaterial;
				}
					
				var mat : AMaterial = _generateMaterial( ref , scene , matType , bCompress , w , h );
				_hCache.addItem( ref , mat );	
				
				return mat; 
				
				
			}
			
			
			/**
			* 
			*
			* @param 
			* @return
			*/
			static public function generateTexture( source : *  , scene : GuaScene , bCompress : Boolean = false , w : int = -1 , h : int = -1 ) : Texture {
				
				//
					if( w == -1 && h == -1 && source is ByteArray )
						throw new ArgumentError( );
				
				//
					var 	t : Texture = scene.refContext3D.createTexture( w , h , Context3DTextureFormat.BGRA , false );
						
				
				//
					if( source is BitmapData )
						t.uploadFromBitmapData( source as BitmapData );
					else if( source is BitmapAsset )
						t.uploadFromBitmapData( ( source as BitmapAsset ).bitmapData );
					else if( source is ByteArray )
						if( !bCompress )
							t.uploadFromByteArray( source as ByteArray , 0 );
						else
							t.uploadCompressedTextureFromByteArray( source as ByteArray , 0 );
					
				return t;
			}
			
		// -------o protected
			
			
			/**
			* 
			*
			* @param 
			* @return
			*/
			final protected function _generateMaterial( ref : * , scene : GuaScene , matType : Class = null , bCompress : Boolean = false , w : int = -1, h : int = -1 ) : AMaterial {
				
				var source : * = ref is Class ? new ref( ) : ref;
				if( source is BitmapAsset || source is BitmapData ){
					w = source.width;
					h = source.height;
				}
				
				var 	t : Texture = generateTexture( source , scene , bCompress , w , h  );
				
				var 	mat : BitmapMaterial = new matType( t );
					mat.sourceWidth = w;
					mat.sourceHeight = h;
					mat.refScene = scene;
				
				_hCache.addItem( ref , mat );	
				return mat;
			}
			
			
		// -------o misc

			public static function trc(...args : *) : void {
				Logger.log(AssetManager, args);
			}
			
			/**
			* Return the singleton instance of the class
			* @public
			* @return instance of the class (AssetManager)
			*/
			static public function getInstance() : AssetManager {				
				if( !__instance )
					__instance = new AssetManager( new SingletonEnforcer() );
								
				return __instance;
			}
			
			protected static var __instance			: AssetManager = null;
	}
}

internal class SingletonEnforcer{
	
}
